package com.tpo.jnotes.base.evernote;

import com.evernote.auth.EvernoteAuth;
import com.evernote.auth.EvernoteService;
import com.evernote.clients.ClientFactory;
import com.evernote.clients.NoteStoreClient;
import com.evernote.clients.UserStoreClient;
import com.evernote.edam.error.EDAMNotFoundException;
import com.evernote.edam.error.EDAMSystemException;
import com.evernote.edam.error.EDAMUserException;
import com.evernote.edam.type.Note;
import com.evernote.thrift.TException;
import com.evernote.thrift.transport.TTransportException;

public class BEvernoteUtil
{

    private static final String AUTH_TOKEN =
        "S=s1:U=8c280:E=14b35e1d54b:C=143de30a94e:P=1cd:A=en-devtoken:V=2:H=954d1bca85f3038ede8279e5175f2268";

    public static void createNote( String aTitle, String aText )
    {
        UserStoreClient userStore;
        NoteStoreClient noteStore;
        String newNoteGuid;

        EvernoteAuth evernoteAuth = new EvernoteAuth( EvernoteService.SANDBOX, AUTH_TOKEN );
        ClientFactory factory = new ClientFactory( evernoteAuth );
        try
        {
            userStore = factory.createUserStoreClient();

            boolean versionOk =
                userStore.checkVersion( "Evernote EDAMDemo (Java)",
                    com.evernote.edam.userstore.Constants.EDAM_VERSION_MAJOR,
                    com.evernote.edam.userstore.Constants.EDAM_VERSION_MINOR );

            if( !versionOk )
            {
                System.err.println( "Incompatible Evernote client protocol version" );
                System.exit( 1 );
            }

            noteStore = factory.createNoteStoreClient();

            Note note = new Note();
            note.setTitle( aTitle );
            String content =
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                    + "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">" + "<en-note>"
                    + "<span style=\"color:green;\">" + aText + "</span><br/>" + "</en-note>";
            note.setContent( content );

            Note createdNote = noteStore.createNote( note );
            newNoteGuid = createdNote.getGuid();

            System.out.println( "Successfully created a new note with GUID: " + newNoteGuid );
            System.out.println();
        }
        catch( TTransportException exception )
        {
            exception.printStackTrace();
        }
        catch( TException exception )
        {
            exception.printStackTrace();
        }
        catch( EDAMUserException exception )
        {
            exception.printStackTrace();
        }
        catch( EDAMSystemException exception )
        {
            exception.printStackTrace();
        }
        catch( EDAMNotFoundException exception )
        {
            exception.printStackTrace();
        }

    }
}
